import logging
from datetime import datetime, timedelta
from collections import deque

import requests

from inc.models import db, Department, User, SyncLog, WechatConfig, Group, GroupUser, AdminDepartment, AdminMember
import json

logger = logging.getLogger('WechatSync')


class WeComSync:
    base_url = 'https://api.weixin.qq.com/'

    @staticmethod
    def _make_api_request(url, method='get', params=None, json_data=None, timeout=10):
        """通用API请求方法"""
        try:
            if method.lower() == 'get':
                response = requests.get(url, params=params, timeout=timeout)
            else:
                response = requests.post(url, json=json_data, timeout=timeout)

            response.raise_for_status()
            data = response.json()

            if data.get('errcode') == 0:
                return data
            else:
                logger.error(f"API请求失败: {data.get('errmsg')}")
        except requests.exceptions.RequestException as e:
            logger.error(f"网络请求失败: {str(e)}")
        except Exception as e:
            logger.exception("API请求异常")
        return None

    @staticmethod
    def get_access_token():
        """获取企业微信Access Token"""
        config = WechatConfig.query.first()
        if not config:
            logger.error("未找到企业微信配置")
            return None

        # 检查token是否过期（提前5分钟刷新）
        if config.access_token and config.token_expires > datetime.now():
            return config.access_token

        url = f"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={config.corp_id}&corpsecret={config.corp_secret}"
        data = WeComSync._make_api_request(url)

        if data:
            access_token = data['access_token']
            expires_in = data['expires_in']
            config.access_token = access_token
            config.token_expires = datetime.now() + timedelta(seconds=expires_in - 300)
            db.session.commit()
            return access_token

        return None

    @staticmethod
    def get_departments():
        """获取所有部门"""
        access_token = WeComSync.get_access_token()
        if not access_token:
            return None

        url = f"https://qyapi.weixin.qq.com/cgi-bin/department/list"
        params = {"access_token": access_token}
        data = WeComSync._make_api_request(url, params=params)
        return data.get('department', []) if data else None

    @staticmethod
    def get_all_users():
        """获取所有用户（分页处理）"""
        access_token = WeComSync.get_access_token()
        if not access_token:
            return None

        all_users = []
        url = "https://qyapi.weixin.qq.com/cgi-bin/user/list"
        params = {
            "access_token": access_token,
            "department_id": 1,
            "fetch_child": 1,
        }

        while True:
            data = WeComSync._make_api_request(url, params=params, timeout=15)
            if not data:
                return None

            all_users.extend(data.get('userlist', []))

            if not data.get('has_more', False):
                break

            params['cursor'] = data.get('next_cursor')

        return all_users

    def sort_departments_by_hierarchy(self, departments):
        """按层级对部门进行排序，确保父部门在子部门之前处理"""
        # 构建部门ID到部门的映射
        dept_dict = {dept['id']: dept for dept in departments}

        # 计算每个部门的层级深度
        def calculate_depth(dept_id, depth=0):
            if dept_id == 0 or dept_id == 1:  # 根部门
                return depth
            dept = dept_dict.get(dept_id)
            if not dept or dept.get('parentid') in (0, 1):  # 父部门是根部门
                return depth + 1
            return calculate_depth(dept.get('parentid'), depth + 1)

        # 为每个部门添加深度属性
        for dept in departments:
            dept['depth'] = calculate_depth(dept.get('parentid', 0))

        # 按深度排序（深度小的先处理）
        return sorted(departments, key=lambda x: x['depth'])

    def sync_departments_and_users(self):
        """同步组织架构和人员信息（完整增量同步版）"""
        log = SyncLog(status='processing', message='同步中...')
        db.session.add(log)
        db.session.commit()

        try:
            # 获取现有的所有部门ID（用于后续删除不存在的部门）
            existing_dept_wecom_ids = {dept.wecom_id for dept in Department.query.all()}
            existing_admin_dept_wecom_ids = {dept.wecom_id for dept in AdminDepartment.query.all()}

            # 获取现有的所有用户ID（用于后续删除不存在的用户）
            existing_user_wecom_ids = {user.wecom_userid for user in User.query.all()}
            existing_admin_member_wecom_ids = {member.wecom_userid for member in AdminMember.query.all() if
                                               member.wecom_userid}

            # 同步部门
            departments = self.get_departments()
            if not departments:
                raise Exception("获取部门数据失败")

            # 使用新的排序方法确保父部门先处理
            departments = self.sort_departments_by_hierarchy(departments)

            # 创建部门映射表：企业微信ID -> 数据库对象
            dept_added = 0
            dept_updated = 0
            wecom_to_local_id = {}  # 企业微信ID -> 数据库ID
            wecom_to_admin_dept_id = {}

            # 记录当前处理的所有部门ID（用于后续删除）
            current_dept_wecom_ids = set()

            # 记录需要二次处理的部门（父部门尚未创建的部门）
            deferred_departments = []

            for dept_data in departments:
                wecom_id = dept_data['id']
                current_dept_wecom_ids.add(wecom_id)  # 记录当前处理的部门ID

                parent_wecom_id = dept_data.get('parentid', 0)

                # 转换父部门ID：企业微信ID -> 数据库ID
                parent_local_id = None
                parent_admin_dept_id = None

                if parent_wecom_id != 0:
                    parent_local_id = wecom_to_local_id.get(parent_wecom_id)
                    parent_admin_dept_id = wecom_to_admin_dept_id.get(parent_wecom_id)

                    # 如果父部门尚未创建，将此部门推迟处理
                    if parent_wecom_id and not parent_local_id:
                        logger.warning(f"父部门 {parent_wecom_id} 尚未创建，将稍后处理部门 {wecom_id}")
                        deferred_departments.append(dept_data)
                        continue

                # 查找或创建部门
                department = Department.query.filter_by(wecom_id=wecom_id).first()
                if not department:
                    department = Department(
                        wecom_id=wecom_id,
                        name=dept_data['name'],
                        parent_id=parent_local_id,  # 使用数据库ID
                        order=dept_data.get('order', 0)
                    )
                    db.session.add(department)
                    dept_added += 1
                else:
                    # 更新现有部门
                    updated = False
                    if department.name != dept_data['name']:
                        department.name = dept_data['name']
                        updated = True
                    if department.parent_id != parent_local_id:
                        department.parent_id = parent_local_id
                        updated = True
                    if department.order != dept_data.get('order', 0):
                        department.order = dept_data.get('order', 0)
                        updated = True
                    if updated:
                        dept_updated += 1

                # 同时更新后台管理部门
                admin_department = AdminDepartment.query.filter_by(wecom_id=wecom_id).first()
                if not admin_department:
                    admin_department = AdminDepartment(
                        name=dept_data['name'],
                        parent_id=parent_admin_dept_id,
                        wecom_id=wecom_id,
                        order_num=dept_data.get('order', 0),
                        create_time=datetime.now(),
                        update_time=datetime.now()
                    )
                    db.session.add(admin_department)
                else:
                    # 更新现有后台管理部门
                    admin_department.name = dept_data['name']
                    admin_department.parent_id = parent_admin_dept_id
                    admin_department.order_num = dept_data.get('order', 0)
                    admin_department.update_time = datetime.now()

                # 刷新ID映射
                db.session.flush()  # 确保获取自增ID
                wecom_to_local_id[wecom_id] = department.id
                wecom_to_admin_dept_id[wecom_id] = admin_department.id

            # 处理被推迟的部门（二次处理）
            max_retries = 5  # 最大重试次数，防止无限循环
            retry_count = 0

            while deferred_departments and retry_count < max_retries:
                retry_count += 1
                logger.info(f"第 {retry_count} 次尝试处理被推迟的部门，剩余 {len(deferred_departments)} 个部门")

                still_deferred = []

                for dept_data in deferred_departments:
                    wecom_id = dept_data['id']
                    parent_wecom_id = dept_data.get('parentid', 0)

                    # 转换父部门ID：企业微信ID -> 数据库ID
                    parent_local_id = None
                    parent_admin_dept_id = None

                    if parent_wecom_id != 0:
                        parent_local_id = wecom_to_local_id.get(parent_wecom_id)
                        parent_admin_dept_id = wecom_to_admin_dept_id.get(parent_wecom_id)

                        # 如果父部门仍然不存在，继续推迟
                        if parent_wecom_id and not parent_local_id:
                            still_deferred.append(dept_data)
                            continue

                    # 查找或创建部门
                    department = Department.query.filter_by(wecom_id=wecom_id).first()
                    if not department:
                        department = Department(
                            wecom_id=wecom_id,
                            name=dept_data['name'],
                            parent_id=parent_local_id,  # 使用数据库ID
                            order=dept_data.get('order', 0)
                        )
                        db.session.add(department)
                        dept_added += 1
                    else:
                        # 更新现有部门
                        updated = False
                        if department.name != dept_data['name']:
                            department.name = dept_data['name']
                            updated = True
                        if department.parent_id != parent_local_id:
                            department.parent_id = parent_local_id
                            updated = True
                        if department.order != dept_data.get('order', 0):
                            department.order = dept_data.get('order', 0)
                            updated = True
                        if updated:
                            dept_updated += 1

                    # 同时更新后台管理部门
                    admin_department = AdminDepartment.query.filter_by(wecom_id=wecom_id).first()
                    if not admin_department:
                        admin_department = AdminDepartment(
                            name=dept_data['name'],
                            parent_id=parent_admin_dept_id,
                            wecom_id=wecom_id,
                            order_num=dept_data.get('order', 0),
                            create_time=datetime.now(),
                            update_time=datetime.now()
                        )
                        db.session.add(admin_department)
                    else:
                        # 更新现有后台管理部门
                        admin_department.name = dept_data['name']
                        admin_department.parent_id = parent_admin_dept_id
                        admin_department.order_num = dept_data.get('order', 0)
                        admin_department.update_time = datetime.now()

                    # 刷新ID映射
                    db.session.flush()  # 确保获取自增ID
                    wecom_to_local_id[wecom_id] = department.id
                    wecom_to_admin_dept_id[wecom_id] = admin_department.id

                deferred_departments = still_deferred

            # 如果还有部门无法处理，记录错误
            if deferred_departments:
                logger.error(f"无法处理 {len(deferred_departments)} 个部门，可能是父部门不存在或数据不一致")
                for dept_data in deferred_departments:
                    logger.error(
                        f"无法处理的部门: ID={dept_data['id']}, 名称={dept_data['name']}, 父部门ID={dept_data.get('parentid', 0)}")

            # 删除不存在的部门
            dept_to_delete = existing_dept_wecom_ids - current_dept_wecom_ids
            if dept_to_delete:
                Department.query.filter(Department.wecom_id.in_(dept_to_delete)).delete(synchronize_session=False)
                logger.info(f"删除了 {len(dept_to_delete)} 个不存在的部门")

            # 删除不存在的后台管理部门
            admin_dept_to_delete = existing_admin_dept_wecom_ids - current_dept_wecom_ids
            if admin_dept_to_delete:
                AdminDepartment.query.filter(AdminDepartment.wecom_id.in_(admin_dept_to_delete)).delete(
                    synchronize_session=False)
                logger.info(f"删除了 {len(admin_dept_to_delete)} 个不存在的后台管理部门")

            db.session.commit()

            # 辅助函数：递归查找公司层级
            def get_company_name(dept_wecom_id):
                """通过企业微信部门ID向上追溯公司层级名称"""
                current_id = dept_wecom_id
                depth = 0

                while depth < 10:  # 防止无限循环
                    # 获取当前部门数据
                    dept = next(
                        (d for d in departments if d['id'] == current_id),
                        None
                    )
                    if not dept:
                        return None

                    parent_wecom_id = dept.get('parentid', 0)

                    # 根部门（企业微信ID=1）的直接子部门即为公司
                    if parent_wecom_id == 1:
                        return dept['name']

                    # 继续向上追溯
                    current_id = parent_wecom_id
                    depth += 1

                return None

            # 同步用户
            all_users = self.get_all_users()
            if not all_users:
                raise Exception("获取用户数据失败")

            users_added = 0
            users_updated = 0
            current_user_wecom_ids = set()  # 记录当前处理的所有用户ID

            for user_data in all_users:
                user_id = user_data['userid']
                current_user_wecom_ids.add(user_id)  # 记录当前处理的用户ID

                # 处理主部门（企业微信ID）
                main_dept_wecom_id = None
                if 'main_department' in user_data:
                    main_dept_wecom_id = user_data['main_department']
                else:
                    depts = user_data.get('department', [])
                    main_dept_wecom_id = depts[0] if depts else None

                # 转换为数据库部门ID
                main_dept_local_id = wecom_to_local_id.get(main_dept_wecom_id) if main_dept_wecom_id else None
                main_admin_dept_id = wecom_to_admin_dept_id.get(main_dept_wecom_id) if main_dept_wecom_id else None

                # 获取公司名称（用于标签）
                company_name = None
                if main_dept_wecom_id:
                    company_name = get_company_name(main_dept_wecom_id)

                # 处理企业微信标签
                tag_ids = user_data.get('tags', [])
                wecom_tags_str = ','.join(map(str, tag_ids)) if tag_ids else None

                # 构建完整的标签字符串（包含公司标签）
                full_tags_str = wecom_tags_str if wecom_tags_str else ""
                if company_name:
                    company_tag = f"{company_name}"
                    if full_tags_str:
                        full_tags_str += f",{company_tag}"
                    else:
                        full_tags_str = company_tag

                # 更新或创建用户
                if user_id in existing_user_wecom_ids:
                    user = User.query.filter_by(wecom_userid=user_id).first()
                    if not user:
                        continue

                    updated = False

                    # 更新基础字段
                    fields_to_check = [
                        ('name', user_data.get('name', '')),
                        ('mobile', user_data.get('mobile', '')),
                        ('email', user_data.get('email', '')),
                        ('position', user_data.get('position', '')),
                        ('avatar', user_data.get('avatar', '')),
                        ('status', user_data.get('status', 0)),
                        ('department_id', main_dept_local_id),
                    ]

                    for field, new_value in fields_to_check:
                        if getattr(user, field) != new_value:
                            setattr(user, field, new_value)
                            updated = True

                    # 更新标签
                    if user.tags != full_tags_str:
                        user.tags = full_tags_str
                        updated = True

                    if updated:
                        users_updated += 1
                else:
                    # 创建新用户
                    user = User(
                        wecom_userid=user_id,
                        name=user_data.get('name', ''),
                        mobile=user_data.get('mobile', ''),
                        email=user_data.get('email', ''),
                        position=user_data.get('position', ''),
                        avatar=user_data.get('avatar', ''),
                        status=user_data.get('status', 0),
                        department_id=main_dept_local_id,
                        tags=full_tags_str
                    )
                    db.session.add(user)
                    users_added += 1

                # 同时更新后台管理员工
                if user_id in existing_admin_member_wecom_ids:
                    admin_member = AdminMember.query.filter_by(wecom_userid=user_id).first()
                    if admin_member:
                        # 更新现有员工
                        admin_member.name = user_data.get('name', '')
                        admin_member.mobile = user_data.get('mobile', '')
                        admin_member.email = user_data.get('email', '')
                        admin_member.position = user_data.get('position', '')
                        admin_member.department_id = main_admin_dept_id
                        admin_member.status = user_data.get('status', 1) == 1  # 1为激活状态
                else:
                    # 创建新员工
                    admin_member = AdminMember(
                        name=user_data.get('name', ''),
                        mobile=user_data.get('mobile', ''),
                        email=user_data.get('email', ''),
                        department_id=main_admin_dept_id,
                        position=user_data.get('position', ''),
                        status=user_data.get('status', 1) == 1,  # 1为激活状态
                        wecom_userid=user_id,
                        create_time=datetime.now()
                    )
                    # 为新员工设置默认密码（手机号后6位）
                    default_password = user_data.get('mobile', '123456')[-6:]  # 取手机号后6位，若无则用123456
                    admin_member.set_password(default_password)
                    db.session.add(admin_member)

            # 删除不存在的用户
            users_to_delete = existing_user_wecom_ids - current_user_wecom_ids
            if users_to_delete:
                User.query.filter(User.wecom_userid.in_(users_to_delete)).delete(synchronize_session=False)
                logger.info(f"删除了 {len(users_to_delete)} 个不存在的用户")

            # 删除不存在的后台管理员工
            admin_members_to_delete = existing_admin_member_wecom_ids - current_user_wecom_ids
            if admin_members_to_delete:
                AdminMember.query.filter(AdminMember.wecom_userid.in_(admin_members_to_delete)).delete(
                    synchronize_session=False)
                logger.info(f"删除了 {len(admin_members_to_delete)} 个不存在的后台管理员工")

            db.session.commit()

            # 更新同步日志
            log.status = 'success'
            log.message = '同步完成'
            log.departments_added = dept_added
            log.departments_updated = dept_updated
            log.users_added = users_added
            log.users_updated = users_updated
            db.session.commit()
            return True
        except Exception as e:
            db.session.rollback()
            if log:
                log.status = 'failure'
                log.message = str(e)
                db.session.commit()
            logger.exception("同步失败")
            return False


################群聊核心代码开始############################
    # 创建群聊 (官方文档: https://developer.work.weixin.qq.com/document/path/90245)
    @staticmethod
    def create_app_chat(name, owner, userlist=None):
        """创建企业微信群聊"""
        access_token = WeComSync.get_access_token()
        if not access_token:
            return None

        url = f"https://qyapi.weixin.qq.com/cgi-bin/appchat/create?access_token={access_token}"
        payload = {
            "name": name,
            "owner": owner,
            "userlist": userlist or []  # 成员userid列表
        }

        try:
            response = requests.post(url, json=payload, timeout=10)
            data = response.json()

            if data.get('errcode') == 0:
                return data.get('chatid')  # 返回群聊ID
            logger.error(f"创建群聊失败: {data.get('errmsg')}")
        except Exception as e:
            logger.error(f"创建群聊请求异常: {str(e)}")
        return None

    # 修改群聊 (官方文档: https://developer.work.weixin.qq.com/document/path/90246)
    @staticmethod
    def update_app_chat(chatid, **kwargs):
        """修改群聊信息"""
        access_token = WeComSync.get_access_token()
        if not access_token:
            return False

        url = f"https://qyapi.weixin.qq.com/cgi-bin/appchat/update?access_token={access_token}"
        payload = {"chatid": chatid}

        # 只添加存在的参数
        valid_params = ["name", "owner", "add_user_list", "del_user_list", "announcement"]
        for key, value in kwargs.items():
            if key in valid_params and value is not None:
                payload[key] = value

        try:
            response = requests.post(url, json=payload, timeout=10)
            data = response.json()

            if data.get('errcode') == 0:
                return True
            logger.error(f"更新群聊失败: {data.get('errmsg')}")
        except Exception as e:
            logger.error(f"更新群聊请求异常: {str(e)}")
        return False

    # 获取群聊信息 (官方文档: https://developer.work.weixin.qq.com/document/path/90247)
    @staticmethod
    def get_app_chat(chatid):
        """获取群聊详情"""
        access_token = WeComSync.get_access_token()
        if not access_token:
            return None

        url = f"https://qyapi.weixin.qq.com/cgi-bin/appchat/get?access_token={access_token}&chatid={chatid}"

        try:
            response = requests.get(url, timeout=10)
            data = response.json()

            if data.get('errcode') == 0:
                return data.get('chat_info')  # 返回群聊信息
            logger.error(f"获取群聊信息失败: {data.get('errmsg')}")
        except Exception as e:
            logger.error(f"获取群聊请求异常: {str(e)}")
        return None

    @staticmethod
    def debug_api_request(url, payload):
        """记录详细的API请求信息（完整实现）"""
        logger.debug(f"API调试请求: {url}")

        try:
            # 记录请求头
            headers = {
                'User-Agent': 'Mozilla/5.0 (compatible; MyApp/1.0)',
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
            logger.debug(f"请求头: {json.dumps(headers)}")
            logger.debug(f"请求体: {json.dumps(payload)}")

            # 发送请求
            response = requests.post(url, json=payload, headers=headers, timeout=15)

            # 记录响应信息
            logger.debug(f"响应状态码: {response.status_code}")

            # 尝试记录响应头（过滤敏感信息）
            response_headers = dict(response.headers)
            if 'Set-Cookie' in response_headers:
                response_headers['Set-Cookie'] = '**REDACTED**'
            logger.debug(f"响应头: {json.dumps(response_headers)}")

            # 记录响应体（限制长度）
            response_text = response.text
            logger.debug(f"响应体 (前500字符): {response_text[:500]}")

            # 尝试解析JSON（如果可能）
            try:
                json_data = response.json()
                logger.debug(f"JSON响应: {json.dumps(json_data, indent=2)}")
            except json.JSONDecodeError:
                logger.debug("响应不是有效的JSON")

            return response
        except Exception as e:
            logger.debug(f"调试请求异常: {str(e)}")
            raise

    # 解散群聊 (官方文档: https://developer.work.weixin.qq.com/document/path/90244)
    @staticmethod
    def disband_app_chat(chatid):
        """精简版解散方法"""
        access_token = WeComSync.get_access_token()
        if not access_token:
            return False

        url = f"https://qyapi.weixin.qq.com/cgi-bin/appchat/del?access_token={access_token}"
        payload = {"chatid": chatid}

        try:
            print(f"发送请求，群聊ID: {chatid}")
            response = requests.post(url, json=payload, timeout=15)
            data = response.json()
            print(f"API响应数据: {data}")
            if data.get('errcode') != 0:
                print(f"解散失败，错误码: {data.get('errcode')}, 错误信息: {data.get('errmsg')}")
                return False
            return True
        except requests.exceptions.RequestException as e:
            print(f"请求错误: {str(e)}")
            return False
        except Exception as e:
            print(f"其他错误: {str(e)}")
            return False

    # 新增群成员同步方法
    def auto_add_users_by_tags(self):
        """自动按标签添加用户到关联群组"""
        # 获取所有配置了标签的群组
        tagged_groups = Group.query.filter(
            Group.assigned_tags != None,
            Group.assigned_tags != '',
            Group.status == Group.ACTIVE
        ).all()

        for group in tagged_groups:
            tags = [t.strip() for t in group.assigned_tags.split(',')]
            self.add_users_by_tag_to_group(group.id, tags)

    @staticmethod
    def add_users_by_tag_to_group(group_id, tag_names):
        """根据标签添加用户到群组（修复版）"""
        group = Group.query.get(group_id)
        if not group:
            return False

        # 分批次添加（每次50人）
        batch_size = 50
        query = User.query
        for tag in tag_names:
            query = query.filter(User.tags.contains(tag))

        users = query.all()

        # 获取现有成员
        existing_members = {gu.user_id for gu in group.members}

        for i in range(0, len(users), batch_size):
            batch = users[i:i + batch_size]
            # 过滤已存在成员
            new_users = [u for u in batch if u.id not in existing_members]

            if not new_users:
                continue

            wecom_userids = [u.wecom_userid for u in new_users]

            if WeComSync.update_app_chat(
                    group.chat_id,
                    add_user_list=wecom_userids
            ):
                # 更新本地数据库
                for user in new_users:
                    db.session.add(GroupUser(
                        group_id=group.id,
                        user_id=user.id,
                        status=GroupUser.ACTIVE
                    ))
                db.session.commit()

        return True

    @staticmethod
    def sync_group_members(chatid):
        """同步群成员（实际实现）"""
        chat_info = WeComSync.get_app_chat(chatid)
        if not chat_info:
            return False

        # 获取群组本地记录
        group = Group.query.filter_by(chat_id=chatid).first()
        if not group:
            return False

        # 获取当前群成员的企业微信ID
        current_member_wecom_ids = set()
        for member in chat_info.get('member_list', []):
            current_member_wecom_ids.add(member['userid'])

        # 获取本地数据库中有效的用户（状态为激活）
        local_active_users = User.query.filter(User.status == 1).all()  # 假设状态1为激活
        local_active_wecom_ids = {u.wecom_userid for u in local_active_users}

        # 应该留在群里的成员：既是当前群成员又是本地激活用户
        valid_wecom_ids = current_member_wecom_ids & local_active_wecom_ids

        # 需要移除的成员：当前群成员中不在本地激活用户中的成员
        remove_wecom_ids = current_member_wecom_ids - local_active_wecom_ids

        # 需要添加的成员：本地激活用户中不在当前群成员中的成员
        add_wecom_ids = local_active_wecom_ids - current_member_wecom_ids

        # 移除无效成员
        if remove_wecom_ids:
            WeComSync.update_app_chat(
                group.chat_id,
                del_user_list=list(remove_wecom_ids)
            )

        # 添加缺失的有效成员
        if add_wecom_ids:
            WeComSync.update_app_chat(
                group.chat_id,
                add_user_list=list(add_wecom_ids)
            )

        # 更新本地数据库成员关系
        GroupUser.query.filter_by(group_id=group.id).delete()

        # 添加有效的成员关系
        for wecom_id in valid_wecom_ids | add_wecom_ids:
            user = User.query.filter_by(wecom_userid=wecom_id).first()
            if user:
                db.session.add(GroupUser(
                    group_id=group.id,
                    user_id=user.id,
                    status=GroupUser.ACTIVE
                ))

        db.session.commit()
        return True

    @staticmethod
    def sync_group_by_tags(group_id):
        """根据标签同步群组成员"""
        group = Group.query.get(group_id)
        if not group or not group.assigned_tags:
            return False, "群组未设置标签"

        # 获取应该加入群组的用户
        users_to_add = group.get_non_member_users()

        if not users_to_add:
            return True, "没有需要添加的新成员"

        # 分批添加用户
        wecom_userids = [u.wecom_userid for u in users_to_add]
        batch_size = 50
        added_count = 0

        for i in range(0, len(wecom_userids), batch_size):
            batch = wecom_userids[i:i + batch_size]
            if WeComSync.update_app_chat(
                    group.chat_id,
                    add_user_list=batch
            ):
                # 更新本地数据库
                for user in users_to_add[i:i + batch_size]:
                    if not GroupUser.query.filter_by(group_id=group_id, user_id=user.id).first():
                        db.session.add(GroupUser(
                            group_id=group_id,
                            user_id=user.id,
                            status=GroupUser.ACTIVE
                        ))
                added_count += len(batch)

        db.session.commit()
        return True, f"成功添加 {added_count} 位成员"

    @staticmethod
    def remove_non_matching_members(group_id):
        """移除不符合标签要求的成员"""
        group = Group.query.get(group_id)
        if not group or not group.assigned_tags:
            return False, "群组未设置标签"

        # 获取符合标签的用户
        matching_users = group.get_matching_users()
        matching_user_ids = {u.id for u in matching_users}

        # 找出不符合标签的现有成员
        non_matching_members = [
            gu for gu in group.members
            if gu.user_id not in matching_user_ids
        ]

        if not non_matching_members:
            return True, "没有需要移除的成员"

        # 从企业微信移除
        wecom_userids = [
            gu.user.wecom_userid for gu in non_matching_members
            if gu.user and gu.user.wecom_userid
        ]

        if wecom_userids and WeComSync.update_app_chat(
                group.chat_id,
                del_user_list=wecom_userids
        ):
            # 更新本地数据库
            for member in non_matching_members:
                db.session.delete(member)

            db.session.commit()
            return True, f"已移除 {len(non_matching_members)} 位不符合标签的成员"

        return False, "移除成员失败"